<template>
  <div class="person-container flex-column">
    <Breadcrumb>
      <template #bread-name>
        个性错题本-{{ studentInfo.studentName }}
      </template>
      <template #bread-right>
        <div class="select-box flex">
          <el-select
            v-model="search.stageOption"
            style="width: 120px"
            :disabled="true"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="search.timeRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
          />
        </div>
      </template>
    </Breadcrumb>
    <main class="person-content flex">
      <ul class="person-left">
        <div class="title">练习任务列表</div>
        <el-empty v-if="!taskList.length"></el-empty>
        <li
          class="task-item flex-between"
          :class="index === activeTaskIndex && 'task-item-active'"
          @click="onSelectTask(index)"
          v-for="(task, index) in taskList"
          :key="index"
        >
          <span :title="task.task_name" class="task-name text-ellipsis hover">{{
            task.task_name
          }}</span>
          <span>{{ task.question_count }}道</span>
        </li>
      </ul>
      <div class="person-right">
        <div class="select-tool flex">
          <el-select
            v-model="questionType"
            placeholder="请选择题型"
            style="width: 240px"
            clearable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            multiple
          >
            <el-option
              v-for="item in questionTypeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select style="width: 120px" v-model="retrainType">
            <el-option
              v-for="item in retrainOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="desc">
          共找到符合条件错题： <span class="text">{{ pageInfo.total }}</span
          >道 &nbsp;&nbsp;&nbsp;&nbsp; 本页共
          <span class="text">{{ questionList.length }}</span>
          道题目 &nbsp;&nbsp;&nbsp;
          <el-button
            text
            type="primary"
            @click="onAddBasket"
            :disabled="!questionList.length"
            >本页全选</el-button
          >
        </div>
        <el-empty v-if="!questionList.length" />
        <AssignTopic
          v-for="(question, index) in questionList"
          :key="index"
          :index="index + 1"
          :topic-data="question"
        />

        <el-pagination
          v-if="pageInfo.total"
          class="flex-end"
          layout="prev, pager, next"
          :total="pageInfo.total"
          v-model:current-page="pageInfo.pageIndex"
          @change="getStudentRetrainQuestionInfo"
        />
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, watchEffect, reactive, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore, useTaskStore } from '@/stores'
import { storeToRefs } from 'pinia'
import {
  getStudentRetrainTask,
  getQuestionType,
  getStudentRetrainQuestion
} from '@/apis/assignment/index'
import { subjectMap, gradeMap } from '@/constants/subject-map'
import Breadcrumb from '@/components/Breadcrumb.vue'
import dayjs from 'dayjs'
import AssignTopic from '../components/AssignTopic.vue'

const route = useRoute()
const { nowGlobalStageId, nowGlobalSubjectId, nowGlobalRole, userInfo } =
  storeToRefs(useAuthStore())
const taskStore = useTaskStore()

const taskList = ref([])
const activeTaskIndex = ref(null)
const options = computed(() => [
  {
    value: '1',
    label: `${gradeMap[nowGlobalStageId.value]}${subjectMap[nowGlobalSubjectId.value]}`
  }
])
const search = reactive({
  stageOption: options.value[0].value,
  timeRange: []
})
const studentInfo = ref({
  studentId: '',
  studentName: ''
})
const questionTypeOption = ref([]) // 题型选项
const questionType = ref([])

const retrainOption = [
  {
    value: '-1',
    label: '全部'
  },
  {
    value: '1',
    label: '已重练'
  },
  {
    value: '0',
    label: '未重练'
  }
]
const retrainType = ref('-1') // 重练状态
const questionList = ref([])
const pageInfo = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 获取学生任务列表
const getStudentRetrainTaskInfo = async () => {
  if (!studentInfo.value.studentId) return
  activeTaskIndex.value = null
  const res = await getStudentRetrainTask({
    school_id: userInfo.value.school_id,
    role_code: nowGlobalRole.value.role_code,
    teacher_id: userInfo.value.userId,
    student_id: studentInfo.value.studentId,
    start_time: search.timeRange?.length
      ? dayjs(search.timeRange[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      : null,
    end_time: search.timeRange?.length
      ? dayjs(search.timeRange[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      : null,
    subject_id: nowGlobalSubjectId.value
  })
  taskList.value = res.data || []
  if (taskList.value.length) {
    activeTaskIndex.value = 0
  } else {
    activeTaskIndex.value = null
  }
}

// 获取题型
const getQuestionTypeInfo = async () => {
  const res = await getQuestionType({
    subject_id: nowGlobalSubjectId.value,
    stage_id: nowGlobalStageId.value
  })
  questionTypeOption.value = res.data.map(item => ({
    value: item.data.id,
    label: item.data.name
  }))
  questionType.value = questionTypeOption.value.map(item => item.value)
}

// 获取学生的重练错题(错题反扫)
const getStudentRetrainQuestionInfo = async () => {
  questionList.value = []

  if (activeTaskIndex.value == null) return
  const res = await getStudentRetrainQuestion({
    task_id: taskList.value[activeTaskIndex.value].task_id,
    question_type: questionType.value.join(','),
    subject_id: nowGlobalSubjectId.value,
    retrain_status: retrainType.value,
    page: pageInfo.value.pageIndex,
    page_size: pageInfo.value.pageSize,
    teacher_id: userInfo.value.userId,
    student_id: studentInfo.value.studentId,
    school_id: userInfo.value.school_id,
    role_code: nowGlobalRole.value.role_code
  })
  pageInfo.value.total = res.data.total
  questionList.value = res.data.list || []
}

const onSelectTask = index => {
  pageInfo.value = {
    pageIndex: 1,
    pageSize: 10,
    total: 0
  }
  activeTaskIndex.value = index
  questionType.value = questionTypeOption.value.map(item => item.value)
  retrainType.value = '-1'
}
// 题目数据加入选题篮中
const onAddBasket = () => {
  let list = questionList.value.map(item => ({
    topic_id: item.id,
    topic_type: item.type,
    is_similar: 0,
    relation_id: 0,
    question_detail: item,
    source: item.source,
    subject_id: item.subject
  }))
  taskStore.setTaskList(list, true)
}

watchEffect(() => {
  getStudentRetrainTaskInfo()
})

watch(
  [questionType, activeTaskIndex, retrainType, nowGlobalRole],
  () => {
    getStudentRetrainQuestionInfo()
  },
  {
    deep: true
  }
)
watch(
  [nowGlobalStageId, nowGlobalSubjectId],
  () => {
    getQuestionTypeInfo()
  },
  {
    deep: true,
    immediate: true
  }
)

const disabledDate = time => {
  return time.getTime() > Date.now()
}

const initData = () => {
  studentInfo.value = {
    studentId: route.query.studentId,
    studentName: route.query.studentName
  }
  search.timeRange = [
    route.query.startTime || null,
    route.query.endTime || null
  ]
}

initData()
</script>

<style lang="less" scoped>
.person-container {
  height: calc(100vh - 60px);
  overflow: hidden;
  .select-box {
    gap: 20px;
  }
  .person-content {
    margin-top: 20px;
    gap: 20px;
    align-items: self-start;
    flex: 1;
    .person-left {
      height: 100%;
      width: 320px;
      overflow: auto;
      background-color: #fff;
      padding: 10px;
      box-sizing: border-box;
      overflow: hidden;
      .title {
        font-size: 18px;
        margin-bottom: 10px;
        font-weight: bold;
      }
      .task-item {
        margin-bottom: 4px;
        line-height: 2.6;
        padding: 0 10px;
        border-radius: 10px;
        &:hover {
          background-color: #f7f9ff;
          color: #1a70e8;
          cursor: pointer;
        }
        .task-name {
          max-width: 80%;
        }
      }
      .task-item-active {
        background-color: #f7f9ff;
        color: #1a70e8;
      }
    }
    .person-right {
      max-height: calc(100vh - 110px);
      box-sizing: border-box;

      padding: 20px;
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .select-tool {
        gap: 20px;
      }
      .desc {
        margin: 20px 0;
        .text {
          color: @theme-color;
        }
      }
    }
  }
}
</style>
